import React, { Component } from 'react'
import {
  Card,
  Form,
  Breadcrumb,
  Button,
  Input,
  Space,
  Radio,
  Upload,
  Modal,
  message,
} from 'antd'
import { Link } from 'react-router-dom'
import MyChannel from 'components/MyChannel'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
// scss 导入 使用 !!!
import styles from './index.module.scss'
import { UploadOutlined } from '@ant-design/icons'
import { baseURL } from 'utils/request'
import { getArticleList, getArticle, editArticleById } from 'api/article'

export default class ArticlePublish extends Component {
  state = {
    type: 1,
    previewImage: '',
    previewVisible: false,
    fileList: [],
    isEdit: !!this.props.match?.params?.id,
    id: this.props.match?.params?.id,
  }
  formRef = React.createRef()
  render() {
    const { type, fileList, previewImage, previewVisible } = this.state
    return (
      <div className={styles.publish}>
        <Card // 面包屑导航
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item>
                <Link to="/layout">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                {this.state.isEdit ? '修改文章' : '发布文章'}
              </Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            ref={this.formRef}
            labelCol={{ span: 4 }}
            onFinish={this.onFinish}
            initialValues={{ title: '', content: '', type }}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: '请输入文章标题' }]}
            >
              <Input
                placeholder="请输入文章标题"
                style={{ width: 400 }}
              ></Input>
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: '请选择频道' }]}
            >
              <MyChannel></MyChannel>
            </Form.Item>
            <Form.Item label="封面" name="type">
              <Radio.Group onChange={this.handleTypeChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {type !== 0 && (
              <Form.Item wrapperCol={{ offset: 4 }}>
                <Upload
                  listType="picture-card"
                  fileList={fileList}
                  name="image"
                  action={`${baseURL}upload`}
                  onChange={this.handleFileChange}
                  method="POST"
                  onPreview={this.handleShow}
                >
                  {fileList.length < type && <UploadOutlined />}
                </Upload>
              </Form.Item>
            )}
            <Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: '请输入文章内容' }]}
            >
              <ReactQuill
                theme="snow"
                placeholder="请输入文章内容..."
              ></ReactQuill>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button size="large" type="primary" htmlType="submit">
                  {this.state.isEdit ? '修改文章' : '发布文章'}
                </Button>
                <Button onClick={this.addDraft} size="large">
                  存入草稿
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
        <Modal
          visible={previewVisible}
          title="图片预览"
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    )
  }
  // 数据回显
  async componentDidMount() {
    const { id, isEdit } = this.state
    if (isEdit) {
      const {
        data: { title, channel_id, content, cover },
      } = await getArticle(id)
      // 1.state 中更新
      this.setState({
        type: cover.type,
        fileList: cover.images.map((item) => ({ url: item })),
      })
      // 表单数据更新
      this.formRef.current.setFieldsValue({
        title,
        channel_id,
        content,
        type: cover.type,
      })
    }
  }
  // 图片上传前的校验
  beforeUpload = (file) => {
    if (file.size / 1024 > 500) {
      message.warning('图片过大')
      return Upload.LIST_IGNOREs
    }
    if (!['image/jepg', 'image/png'].includes(file.type)) {
      message.warning('图片格式不正确')
      return Upload.LIST_IGNOREs
    }
    return true
  }

  // 检测单选框变化 隐藏下面的图片上传
  handleTypeChange = (e) => {
    this.setState({
      type: e.target.value,
      fileList: [],
    })
  }
  // 获取图片成功上传的地址 并且赋值给state中的filelist用于显示
  handleFileChange = ({ file, fileList }) => {
    this.setState({
      fileList,
    })
  }
  // 点击图片预览
  handleShow = (file) => {
    this.setState({
      previewVisible: true,
      previewImage: file.url || file.response.data.url,
    })
  }
  // 取消预览弹框
  handleCancel = () => {
    this.setState({
      previewVisible: false,
    })
  }
  // 抽离 onfonish 中的逻辑
  save = async (values, draft) => {
    const { fileList, isEdit, id } = this.state
    const { type } = values
    if (type !== fileList.length) {
      message.error('上传封面数量不符')
      return
    }
    const imagesArr = fileList.map((item) => item.url || item.response.data.url)
    // console.log(response.data)
    const data = {
      ...values,
      cover: {
        type: values.type,
        images: imagesArr,
      },
    }
    if (isEdit) {
      await editArticleById(id, data, draft)
      message.success('修改成功')
    } else {
      await getArticleList(data, draft)
      message.success('发布成功')
    }
    this.props.history.push('/layout/list')
  }
  // 获取文章数据
  onFinish = async (values) => {
    this.save(values, false)
  }
  // 存入草稿
  addDraft = async () => {
    try {
      const values = await this.formRef.current.validateFields()
      message.success('存入草稿成功')
      this.save(values, true)
    } catch {
      console.log('校验未通过')
    }
  }
}
